﻿using System;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace ActivateYourGlutes.Infrastructure
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public sealed class RequireSslAttribute : FilterAttribute, IAuthorizationFilter
    {
        public RequireSslAttribute()
        {
            Redirect = true;
            Enable = true;
        }

        public bool Redirect { get; set; }

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            //Validate.IsNotNull(filterContext, "filterContext");

            if (!Enable || filterContext.HttpContext.Request.Url.Host.ToLower() == "localhost")
            {
                return;
            }
            
            if (!filterContext.HttpContext.Request.IsSecureConnection)
            {
                // request is not SSL-protected, so throw or redirect 
                if (Redirect)
                {
                    // form new URL 
                    UriBuilder builder = new UriBuilder
                    {
                        Scheme = "https",
                        Host = filterContext.HttpContext.Request.Url.Host,
                        // use the RawUrl since it works with URL Rewriting 
                        Path = filterContext.HttpContext.Request.RawUrl
                    };
                    filterContext.Result = new RedirectResult(builder.ToString());
                }
                else
                {
                    throw new HttpException((int)HttpStatusCode.Forbidden, "Access forbidden. The requested resource requires an SSL connection.");
                }
            }
        }

        public static bool Enable { get; set; }
    } 

}
